import { CustomValidators } from '../../shared/custom-validators/custom-validators';
import { HttpService } from '../../shared/service/http.service';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Component, ElementRef, OnInit, Renderer2, AfterViewInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ActionSheetService } from 'ng-zorro-antd-mobile';
import { ModalController } from '@ionic/angular';

@Component({
  selector: 'app-register-sh',
  templateUrl: './register-sh.component.html',
  styleUrls: ['./register-sh.component.scss'],
})
//tslint:disable
export class RegisterShComponent implements OnInit {
  myForm: FormGroup;
  checked = false;
  private timer: any;
  user: any;
  staffType: any;
  mvcode: any;
  showImgCode = false;
  imgCode: any;
  time = -1;
  isApp = false;
  register = {
    name: '',
    typeName: '',
    phone: '',
    imgcode: '',
    invitation: '',
    vcode: '',
  };
  constructor(
    private appGlobalService: AppGlobalService,
    private route: ActivatedRoute,
    private router: Router,
    private httpService: HttpService,
    private _actionSheet: ActionSheetService, // 必须有
    private renderer2: Renderer2,
    private element: ElementRef,
    private modalCtrl: ModalController,) { }

  ngAfterViewInit() {
    // 修改 ion-item 样式
    const ionBackButton = this.element.nativeElement.querySelector('ion-item');
    const styleSheet = `
          .item-inner {
            border-bottom: solid 0.05rem #E3E5E8 !important;
            padding-inline-end: 0 !important;
          }
      `;
    this.appGlobalService.injectStyleToShadowRoot(this.renderer2, ionBackButton, styleSheet);
  }
  ngOnInit() {
    this.myForm = new FormGroup({
      staffType: new FormControl(null, Validators.minLength(1)),
      name: new FormControl(null, Validators.minLength(2)),
      phone: new FormControl(null, [Validators.minLength(11), Validators.maxLength(11), CustomValidators.phone]),
      invitation: new FormControl(0),
      vcode: new FormControl(null, [Validators.minLength(4), Validators.maxLength(6)]),
      user_type: new FormControl(0)
    });
    if (localStorage.getItem('client') === 'APP') {
      this.isApp = true;
    } else {
      this.isApp = false;
    }
    this.route.queryParams.subscribe(param => {
      console.log('index:' + param.index);
      console.log('invitation:' + param.code);
      this.register.invitation = Number(param.code) > 0 ? param.code : '';
      if (param.user) {
        this.user = JSON.parse(param.user);
      } else {
        // return;
      }
      if (param.staffType) {
        this.staffType = JSON.parse(param.staffType);
        this.register.typeName = this.staffType[param.index].name;
        this.myForm = new FormGroup({
          staffType: new FormControl(null, Validators.minLength(1)),
          name: new FormControl(null, Validators.minLength(2)),
          phone: new FormControl(null, [Validators.minLength(11), Validators.maxLength(11), CustomValidators.phone]),
          invitation: new FormControl(param.code),
          vcode: new FormControl(null, [Validators.minLength(4), Validators.maxLength(6)]),
          // 申请的业务类型：1工人（承接劳务业务）、2设计师（设计业务）、3建材销售业务、4房管家会员业务、5直租直售业务、6房管家工人（会员维修订单业务）
          user_type: new FormControl(param.index === '0' ? 5 : 4)
        });
        this.myForm.patchValue({ staffType: this.staffType[param.index].value });
      }

    });
  }
  checkClick() {
    this.checked = !this.checked;
  }
  xieyiClick() {
    //  this.router.navigate(['user-agreement']);
    this.openArgument();

  }
  async openArgument() {
    this.appGlobalService.openUrl("服务协议", this.appGlobalService.serviceAgreementLink);
  }

  // Operator
  showActionSheet = () => {


    if (!this.staffType) { return; }
    const that = this;
    let lastIndex: -1;
    const buttons: any = [];
    this.staffType.forEach((element, index) => {
      buttons.push(element.name);
      if (this.register.typeName === element.name) {
        lastIndex = index;
      }
    });

    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        // cancelButtonIndex: buttons.length - 1,
        destructiveButtonIndex: lastIndex,
        // title: '选择状态',
        // message: message,
        maskClosable: true
      },
      buttonIndex => {
        console.log(buttonIndex);
        if (buttonIndex <= -1) {
          return;
        }
        that.register.typeName = this.staffType[buttonIndex].name;
        that.myForm.patchValue({ staffType: this.staffType[buttonIndex].value });
        // 申请的业务类型：1工人（承接劳务业务）、2设计师（设计业务）、3建材销售业务、4房管家会员业务、5直租直售业务、6房管家工人（会员维修订单业务）
        that.myForm.patchValue({ user_type: buttonIndex === 0 ? 5 : 4 });
      }
    );
  }

  back() {
    this.appGlobalService.goBack();
  }

  getImgCode() {
    // // tslint:disable-next-line:max-line-length
    this.httpService.http.get(this.httpService.bathUrl + 'userRegister/validateCode?mobile=' +
      encodeURIComponent(this.appGlobalService.encryptDes(this.myForm.value.phone)),
      { responseType: 'text' }).subscribe(
        (data) => {
          if (data) {
            this.imgCode = 'data:image/png;base64,' + decodeURIComponent(data);
            console.log(this.imgCode);
          } else {
            this.imgCode = '';
          }
        },
        (error) => {
        }
      );

  }

  getVC(invalid) {
    console.log(this.myForm.get('phone'));
    if (invalid) {
      this.appGlobalService.showToast('请输入正确手机号码', 2000, 'top');
    } else {
      let params: any;
      if (this.showImgCode) {
        if (this.myForm.get('imgcode').errors) {
          this.appGlobalService.showToast('请输入图形验证码', 2000, 'top');
          return;
        } else {
          params = {
            phone: this.appGlobalService.encryptDes(this.myForm.value.phone),
            vcode: this.appGlobalService.encryptDes(this.myForm.value.imgcode),
            type: 0
          };
        }

      } else {
        params = {
          phone: this.appGlobalService.encryptDes(this.myForm.value.phone),
          type: 0
        };
      }

      this.httpService.post('userRegister/smsSend', params, data => {
        if (data.code === 0) {
          this.appGlobalService.showToast(
            '验证码已发送、请注意查收',
            2000,
            'top'
          );
          if (data.data) {
            this.register.vcode = data.data.code;
          }
          this.time = 90;
          const timer = setInterval(() => {
            this.time = this.time - 1;
            if (this.time === -1) {
              clearInterval(timer);
            }
          }, 1000);

          if (this.myForm.contains('imgcode')) {
            this.myForm.removeControl('imgcode');
            this.showImgCode = false;
          }
        } else if (data.code === 602) {
          this.showImgCode = true;
          if (!this.myForm.contains('imgcode')) {
            this.myForm.addControl('imgcode', new FormControl(null, [Validators.minLength(4), Validators.maxLength(4)]));
          }
          this.getImgCode();
          this.appGlobalService.showToast(data.message, 3000, 'top');
        } else {
          this.appGlobalService.showToast(data.message, 3000, 'top');
        }
      });
    }
  }

  registerClick() {
    if (!this.checked) {
      this.appGlobalService.showToast('勾选且同意蜂喔用户协议才能注册', 1500, 'top');
      return;
    }
    if (this.myForm.valid) {

      console.log(this.myForm.value);
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        const that = this;
        const param = {
          type: 1,
          staffType: this.myForm.value.staffType,
          mobile: this.appGlobalService.encryptDes(this.myForm.value.phone),
          name: this.myForm.value.name,
          // mobile: this.myForm.value.phone,
          vcode: this.appGlobalService.encryptDes(this.myForm.value.vcode),
          invitation: this.myForm.value.invitation,
          user_type: this.myForm.value.user_type
        };
        this.httpService.post('userRegister/register', param, (res => {
          // console.log(JSON.stringify(res));
          if (res.code === 0) {
            if (this.isApp) {
              this.appGlobalService.showToast('申请成功', 1500, 'top');
              this.appGlobalService.goBack();
            } else {
              this.openApp();
            }
          } else {
            if (res.message && res.message.length > 0) {
              this.appGlobalService.showToast(res.message, 1500, 'top');
            } else {
              this.appGlobalService.showToast('注册失败', 1500, 'top');
            }
          }

        }), err => {
          if (err.message && err.message.length > 0) {
            this.appGlobalService.showToast(err.message, 1500, 'top');

          } else {
            this.appGlobalService.showToast('注册失败', 1500, 'top');

          }
        });
      }, 1000);
    } else {
      this.getErrors(this.myForm);
    }
  }
  getErrors(form) {
    const errs = [];
    for (const name in form.controls) {
      // eg: controls[name] = phone
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }

    if (errs.length) {
      const errItem = errs[0];
      console.log(errItem.key[0], '校验的字段名');
      let errMessage = '请输入正确的内容';
      if (errItem.key[0] === 'staffType') {
        errMessage = '请选择申请类型';
      } else
        if (errItem.key[0] === 'name') {
          errMessage = '请填写姓名';
        } else if (errItem.key[0] === 'phone') {
          errMessage = '请填写正确的手机';
        } else if (errItem.key[0] === 'invitation') {
          errMessage = '请填写正确的邀请码';
        } else if (errItem.key[0] === 'vcode') {
          errMessage = '请填写正确的验证码';
        }
      this.appGlobalService.showToast(errMessage, 1500, 'top');
    }
  }

  call() {
    if (this.user && this.user.mobile) {
      document.location.href = 'tel:' + this.user.mobile;
    }
  }

  openApp() {
    if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
      const loadDateTime: any = new Date();
      window.setTimeout(function () {
        const timeOutDateTime: any = new Date();
        if (timeOutDateTime - loadDateTime < 5000) {
          location.href = 'https://a.app.qq.com/o/simple.jsp?pkgname=com.laijian.customer';
        } else {
          window.close();
        }
      }, 25);
      location.href = 'fwsh://';
    } else if (navigator.userAgent.match(/android/i)) {
      const loadDateTime: any = new Date();
      try {
        const state = window.open('fwsh://', '_blank');
        window.setTimeout(function () {
          const timeOutDateTime: any = new Date();
          if (timeOutDateTime - loadDateTime < 5000) {
            location.href = 'https://a.app.qq.com/o/simple.jsp?pkgname=com.laijian.customer';
          } else {
            window.close();
          }
        }, 25);
      } catch (error) {

      }

    }

  }

  async alertPrivacyPolicy() {
    this.appGlobalService.openUrl("隐私权限", this.appGlobalService.privatePolicyLink);
  }


}
